import { login, getInfo } from '@/api/user'
import { Message } from 'element-ui'
import router from '@/router'
export default {
  namespaced: true,
  state() {
    return {
      token: '',
      tokenTime: '',
      userInfo: {}
    }
  },
  getters: {},
  mutations: {
    setToken(state, token) {
      state.token = token
      token ? state.tokenTime = Date.now() : state.tokenTime = ''
    },
    setUserInfo(state, obj) {
      state.userInfo = obj
    }
  },
  actions: {
    async getToken({ commit }, obj) {
      try {
        const res = await login(obj)
        Message.success({
          showClose: true,
          message: res.message
        })
        commit('setToken', res.data)
        setTimeout(() => {
          router.push('/')
        }, 1000)
      } catch {
        console.log('登陆失败')
      }
    },
    async getUserInfo({ commit }) {
      const res = await getInfo()
      commit('setUserInfo', res.data)
    },
    // 退出事件
    logout({ commit }) {
      commit('setToken', '')
      commit('setUserInfo', {})
      Message.error({
        showClose: true,
        message: '登陆状态失败，请重新登录'
      })
      router.push('/login')
    }
  },
  modules: {}
}
